package com.cq.androidtools.jetpack.WorkManager

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.work.*
import com.cq.androidtools.databinding.AcWorkerBinding
import java.util.concurrent.TimeUnit

/**
 * 作者: CQ
 * 日期: 2021-05-24
 * 说明: WorkManager的使用：
 */
class WorkerActivity : AppCompatActivity() {
    private lateinit var workerActivity: AcWorkerBinding

    @SuppressLint("EnqueueWork", "IdleBatteryChargingConstraints")
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        workerActivity = AcWorkerBinding.inflate(layoutInflater)
        setContentView(workerActivity.root)
        workerActivity.OneTimeWorkRequestBuilder.setOnClickListener {
            // 设置传递的数据
//            val inputData = Data.Builder().putString("WorkerActivity", "我想知道你的名字").build()
            val inputData = workDataOf(Pair("WorkerActivity", "我想知道你的名字"))
            // 设置执行条件
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED) // 网络状态
                .setRequiresBatteryNotLow(true)// 不是低电量
                .setRequiresDeviceIdle(true) // 设备待机空闲
                .setRequiresStorageNotLow(true)//内存不紧张
                .setRequiresCharging(true) //充电
                .build()

            val oneTimeWorkRequest = OneTimeWorkRequestBuilder<MyWorker>()
                .setInputData(inputData)
                .setConstraints(constraints)
                .addTag("one")
                .build()
            WorkManager.getInstance(this).enqueue(oneTimeWorkRequest)
            WorkManager.getInstance(this).getWorkInfoByIdLiveData(oneTimeWorkRequest.id)
                .observe(this, Observer {
                    if (it != null && it.state.isFinished) {
                        //在任务执行完成后
                        Log.i("TAG", "activity取到了回传的数据--- " + it.outputData.getString("name"));
                    }
                })
            WorkManager.getInstance(this).cancelAllWork()
        }
        workerActivity.Begin.setOnClickListener {
            val inputData1 = workDataOf(Pair("WorkerActivity", "我想知道你的名字1"))
            val inputData2 = workDataOf(Pair("WorkerActivity", "我想知道你的名字2"))
            val inputData3 = workDataOf(Pair("WorkerActivity", "我想知道你的名字3"))
            val oneTimeWorkRequest1 = OneTimeWorkRequestBuilder<MyWorker>()
                .setInputData(inputData1)
                .build()
            val oneTimeWorkRequest2 = OneTimeWorkRequestBuilder<MyWorker2>()
                .setInputData(inputData2)
                .build()
            val oneTimeWorkRequest3 = OneTimeWorkRequestBuilder<MyWorker3>()
                .setInputData(inputData3)
                .build()
            // 1、2、3依次执行
//            WorkManager.getInstance(this).beginWith(oneTimeWorkRequest1).then(oneTimeWorkRequest2).then(oneTimeWorkRequest3).enqueue()
            // 1和2同时执行，执行完成后再执行3
            WorkManager.getInstance(this)
                .beginWith(mutableListOf(oneTimeWorkRequest1, oneTimeWorkRequest2))
                .then(oneTimeWorkRequest3).enqueue()
        }
        workerActivity.PeriodicWorkRequestBuilder.setOnClickListener {
//            最小周期不能低于15分钟,如果设置小于15分钟,也是按15分钟的周期运行
//            日志会打印:Interval duration lesser than minimum allowed value; Changed to 900000"
            val period = PeriodicWorkRequestBuilder<MyWorker>(2, TimeUnit.SECONDS).build()
            WorkManager.getInstance(this).enqueue(period)

        }

        workerActivity.five.setOnClickListener {
            val inputData1 = workDataOf(Pair("WorkerActivity", "我想知道你的名字1"))
            val inputData2 = workDataOf(Pair("WorkerActivity", "我想知道你的名字2"))
            val inputData3 = workDataOf(Pair("WorkerActivity", "我想知道你的名字3"))
            val inputData4 = workDataOf(Pair("WorkerActivity", "我想知道你的名字4"))
            val inputData5 = workDataOf(Pair("WorkerActivity", "我想知道你的名字5"))
            val oneTimeWorkRequest1 = OneTimeWorkRequestBuilder<MyWorker>()
                .setInputData(inputData1)
                .build()
            val oneTimeWorkRequest2 = OneTimeWorkRequestBuilder<MyWorker2>()
                .setInputData(inputData2)
                .build()
            val oneTimeWorkRequest3 = OneTimeWorkRequestBuilder<MyWorker3>()
                .setInputData(inputData3)
                .build()
            val oneTimeWorkRequest4 = OneTimeWorkRequestBuilder<MyWorker4>()
                .setInputData(inputData4)
                .build()
            val oneTimeWorkRequest5 = OneTimeWorkRequestBuilder<MyWorker5>()
                .setInputData(inputData5)
                .build()
//             chain1和chain2同时执行，都执行完成后再执行oneTimeWorkRequest5
            val chain1 = WorkManager.getInstance(this).beginWith(oneTimeWorkRequest1)
                .then(oneTimeWorkRequest2)
            val chain2 = WorkManager.getInstance(this).beginWith(oneTimeWorkRequest3)
                .then(oneTimeWorkRequest4)
            WorkContinuation.combine(mutableListOf(chain1, chain2)).then(oneTimeWorkRequest5)
                .enqueue()
        }
        workerActivity.lineup.setOnClickListener {
            // 启动两个列队，1开启后，2开启，则把1取消了
//            Work [ id=546c3a11-1683-42ad-b227-45a6d6145ccf, tags={ com.cq.androidtools.jatpack.WorkManager.MyWorker } ] was cancelled
            val inputData1 = workDataOf(Pair("WorkerActivity", "我想知道你的名字1"))
            val inputData2 = workDataOf(Pair("WorkerActivity", "我想知道你的名字2"))
            WorkManager.getInstance(this).beginUniqueWork("two",
                ExistingWorkPolicy.REPLACE,
                OneTimeWorkRequestBuilder<MyWorker>()
                    .setInputData(inputData1)
                    .build()
                    .apply {
                        WorkManager.getInstance(applicationContext).getWorkInfoByIdLiveData(id)
                            .observe({ lifecycle }) {
                                Log.d("TAG", "unique chain: ${it.id}: ${it.state}")
                            }
                    }).enqueue()
            Thread.sleep(300)
            WorkManager.getInstance(this).beginUniqueWork("two",
                ExistingWorkPolicy.REPLACE,
                OneTimeWorkRequestBuilder<MyWorker2>()
                    .setInputData(inputData2)
                    .build()
                    .apply {
                        WorkManager.getInstance(applicationContext).getWorkInfoByIdLiveData(id)
                            .observe({ lifecycle }) {
                                Log.d("TAG", "unique chain: ${it.id}: ${it.state}")
                            }
                    }).enqueue()


        }
    }
}

